package org.osami.commons.dialog.android.androiddisplayservice;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import com.prosyst.mbs.android.MBSConstants;
import com.prosyst.mbs.android.application.ApplicationRegistry;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import org.osami.commons.dialog.IDisplayService;

public class Activator implements BundleActivator {

	private ServiceReference sRefAppReg;
	private ApplicationRegistry appReg;
	private MyApplicationFactory fact;
	private ServiceReference sRefCtx;
	private Context ctx;
	private static final String TAG = "ADS";
	
	public static String tag() {
		return TAG;
	}
	
	public void start(BundleContext context) throws Exception {
		
		Log.i(tag(), "Starting Android Display service");
		sRefAppReg = context.getServiceReference(ApplicationRegistry.class.getName());
	    
		if (sRefAppReg != null) {
			Log.i(tag(), "Service reference for ApplicationRegistry found");
			
	    	appReg = (ApplicationRegistry) context.getService(sRefAppReg);
	    	fact = new MyApplicationFactory();
	    	context.registerService(IDisplayService.class.getName(), fact, null);
	    	
	    	if (appReg.registerApplicationFactory(fact)) {
	    		Log.i(tag(), "Successfully registered application factory");   		
	    	} else {
	    		Log.i(tag(), "Failed to register application factory");
	    	}
	    } else {
	    	Log.i(tag(), "Service reference for ApplicationRegistry not found");
	    }
		
		 // Get the android.content.Context service dedicated for bundles with Android UI. 
	    sRefCtx = context.getServiceReference(Context.class.getName());
	    if (sRefCtx != null) {
	      System.out.println("esmerkki: android-konteksti löyty");
	      ctx = (Context) context.getService(sRefCtx);
	      // Start the activity for OSGi bundles. Set as actions MBS_APPLICATION_ACTION and additionally
	      // set as bundle application type "my.osgi.view" as returned 
	      // by this bundle's application factory.
//	      Intent intent = new Intent(MBSConstants.MBS_APPLICATION_ACTION);
//	      intent.putExtra(MBSConstants.MBS_APPLICATION_TYPE,
//	          UIaktivaattori.MY_OSGI_VIEW);
//	      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//	      ctx.startActivity(intent);
	      
			//start the application
			Intent intent = new Intent(MBSConstants.MBS_APPLICATION_ACTION);
			intent.putExtra(MBSConstants.MBS_APPLICATION_TYPE,
			    fact.MY_OSGI_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			
			ctx.startActivity(intent);	
	    } else {
	    	System.out.println("esmerkki: ei löytyny android-kontekstia.");
	    }
		
	
	
	}

	public void stop(BundleContext context) throws Exception {
		if (appReg != null) {
			appReg.unregisterApplicationFactory(fact);
		}
	}

}
